<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSONToCSV</title>
</head>

<body>
    <div>打开控制台查看结果</div>
    <script>
        const JSONToCSV = (arr, columns, delimiter = ",") =>
            [
                columns.join(delimiter),
                ...arr.map((obj) =>
                    columns.reduce(
                        (res, key) =>
                            `${res}${!res.length ? "" : delimiter}"${!obj[key] ? "" : obj[key]}"`,
                        ""
                    )
                ),
            ].join("\n");
        const data = [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }];
        const columns = ["a", "b"];
        console.log(`JSONToCSV(${JSON.stringify(data)},${JSON.stringify(columns)}):   `, JSONToCSV(data, columns));
        console.log(`JSONToCSV(${JSON.stringify(data)},${JSON.stringify(columns)},';'):    `, JSONToCSV(data, columns, ';'));
    </script>
</body>

</html>